const validate = {

    //验证规则，返回bool值，函数自动处理错误信息
    validate: function (formRules,form,vue){
        return new Promise((resolve, reject) => {
            let formMap = {};
            let formEntries = Object.entries(form)
            formEntries.forEach(param=>{
                formMap[param[0]] = param[1]
            })
            let rules = Object.keys(formRules);
            //遍历 rules
            for (let i = 0; i < rules.length; i++) {
                let rule = rules[i]
                if (!formRules[rule].validate(formMap[rule])) {
                    vue.$message.error(formRules[rule].message)
                    reject(false)
                }
            }
            resolve(true)
        })

    },

    //验证规则，返回错误信息，由调用者处理
    validate_error: function (formRules,form){
        return new Promise((resolve, reject) => {
            let formMap = {};
            let formEntries = Object.entries(form)
            formEntries.forEach(param=>{
                formMap[param[0]] = param[1]
            })
            let rules = Object.keys(formRules);
            //遍历 rules
            for (let i = 0; i < rules.length; i++) {
                let rule = rules[i]
                if (!formRules[rule].validate(formMap[rule])) {
                    reject(formRules[rule].message)
                }
            }
            resolve(form)
        })

    },

    Rule:{
        isEmail: function (email) {
            return /\S+@\S+\.\S+/.test(email);
        },
        //判断是否为空
        isEmpty: function (value) {
            return !(value === undefined || value === null || value === '');
        },
        //判断日期是否大于当前日期
        isDate: function (date) {
            return new Date(date) > new Date();
        },
        //判断日期是否大于今天
        isDateLater: function (date) {
            return new Date(date).getTime()+5*60*1000 >= new Date();
        },
        //判断是否为数字
        isNumber: function (value) {
            return /^[0-9]*$/.test(value);
        },

        //TODO 【TestChange】 测试校验函数，在后期要复原为正则表达式
        isUsername: function (value) {
            //return /^[a-zA-Z0-9_-]{4,16}$/.test(value);
            return true
        },
        isPassword: function (value) {
            //return /^[a-zA-Z0-9_-]{6,18}$/.test(value);
            return true
        },
        isPhone: function (value){
            return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(value);
        }
    }

}

export default validate
